#include "GeneralSettingsPage.h"
#include "ui_GeneralSettingsPage.h"
#include <QDir>
#include <QStringList>
#include <QStyleFactory>
#include <QSettings>

GeneralSettingsPage::GeneralSettingsPage(QWidget* parent)
    : AbstractSettingsPage(parent)
    , ui(new Ui::GeneralSettingsPage)
{
    ui->setupUi(this);
    load();
}

GeneralSettingsPage::~GeneralSettingsPage()
{
    delete ui;
}

void GeneralSettingsPage::changeEvent(QEvent* event)
{
    QWidget::changeEvent(event);
    switch (event->type()) {
    case QEvent::LanguageChange:
        ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

void GeneralSettingsPage::load()
{
    QSettings config;
    _generalSettings.fromSettings(&config);

    // choose language
    ui->cbbLanguage->clear();
    QDir dir(":/i18n");
    QStringList fileNames = dir.entryList(QStringList("*"), QDir::Files, QDir::Name);
    ui->cbbLanguage->addItems(fileNames);
    int languageIndex = ui->cbbLanguage->findText(_generalSettings.language, Qt::MatchFixedString);
    ui->cbbLanguage->setCurrentIndex(languageIndex > -1 ? languageIndex : 0);

    // choose style
    ui->cbbStyle->clear();
    ui->cbbStyle->addItems(QStyleFactory::keys());
    //! "Qt resource protocol" is supported in html fragment. Awsome!
    ui->cbbStyle->setToolTip(tr("<h3>Change application look and feels</h3>"
                             "<p>Samples:</p>"
                             "<p><img src=\":/about/styles-demo\"></p>"));
    int styleIndex = ui->cbbStyle->findText(_generalSettings.style, Qt::MatchFixedString);
    ui->cbbStyle->setCurrentIndex(styleIndex > -1 ? styleIndex : 0);

    // choose font
    int familyIndex = ui->cbbFamily->findText(_generalSettings.font.family(), Qt::MatchFixedString);
    ui->cbbFamily->setCurrentIndex(familyIndex > -1 ? familyIndex : 0);
    ui->cbbSize->setFontSize(_generalSettings.font.pointSize());
}

void GeneralSettingsPage::save()
{
    _generalSettings.language = ui->cbbLanguage->currentText();
    _generalSettings.style = ui->cbbStyle->currentText();
    _generalSettings.font.setFamily(ui->cbbFamily->currentText());
    _generalSettings.font.setPointSize(ui->cbbSize->fontSize());
    QSettings config;
    _generalSettings.toSettings(&config);
}
